﻿using System;
using System.Windows.Forms;
using S7PlcDataManager.S7Plc;
using ZbSkin.Tools;

namespace S7PlcDataManager.Controls
{
    public partial class MainControl : UserControl
    {
        private readonly ConnectControl _connectControl;
        private readonly DataTypeControl _dataTypeControl;
        private readonly DataQueryControl _dataQueryControl;
        private readonly DataSetControl _dataSetControl;

        public MainControl()
        {
            InitializeComponent();

            var s7PlcHelper = new S7PlcHelper();
            _connectControl = new ConnectControl(s7PlcHelper);
            _dataTypeControl = new DataTypeControl();
            _dataQueryControl = new DataQueryControl(s7PlcHelper);
            _dataSetControl = new DataSetControl(s7PlcHelper);

            _dataTypeControl.DataTypeChanged += OnDataTypeChanged;
        }

        private void MainControl_Load(object sender, EventArgs e)
        {
            Controls.Add(_connectControl);
            Controls.Add(_dataTypeControl);
            Controls.Add(_dataQueryControl);
            Controls.Add(_dataSetControl);

            ResizeControls();
        }

        private void MainControl_Resize(object sender, EventArgs e)
        {
            ResizeControls();
        }

        private void ResizeControls()
        {
            var width = ClientSize.Width - 20;
            const int left = 10;
            _connectControl.Width = width;
            _connectControl.Left = left;
            _connectControl.Top = 10;
            _dataTypeControl.Width = width;
            _dataTypeControl.Left = left;
            _dataTypeControl.Top = _connectControl.Bottom + 10;
            _dataQueryControl.Width = width;
            _dataQueryControl.Left = left;
            _dataQueryControl.Top = _dataTypeControl.Bottom + 10;
            _dataSetControl.Width = width;
            _dataSetControl.Left = left;
            _dataSetControl.Top = _dataQueryControl.Bottom + 10;
            this.SetRegion(10);
        }

        private void OnDataTypeChanged()
        {
            var variable = _dataTypeControl.Variable;
            var valueType = _dataTypeControl.ValueType;
            _dataQueryControl.ChangeDataType(variable, valueType);
            _dataSetControl.ChangeDataType(variable, valueType);
        }
    }
}
